<?php

namespace app\order\logic;

use app\common\service\ConstantOrderService;
use app\common\service\TiktokPackageApiService;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\model\Order as OrderModel;
use app\order\model\OrderStatementSku as OrderStatementSkuModel;
use app\order\model\OrderStatement as OrderStatementModel;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;
use app\common\service\JinyiApiService;

class OrderServiceLogic
{

    protected $model = null;

    public function __construct()
    {
        $this->model = new OrderModel();
    }



    /**
     * 同步订单列表-基础信息
     * @param $type
     * @return mixed
     */
    public function syncOrderList($param='')
    {
        $type = $param['type']??'';
        date_default_timezone_set('Asia/Shanghai');
        $shop = Db::name('shops')
               ->order("updatetime_order_shop asc")
               ->find();
        $tik_info  = Config::get('Logisticskey.' . 'TIKTOK');
        $baseUrl   = $tik_info['basic_url'];
        $path      = $tik_info['orders_list_path'];
        switch ($type){
            case 1: //1 查询之前的订单
                if ($shop['updatetime_order']) {
                    $create_time_lt = (int)$shop['updatetime_order'] + $shop['time_zone'] * 3600 + 300; //五分钟
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $create_time_lt = time() + $shop['time_zone'] * 3600;
                }
                $sign = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'page_size50shop_cipher' . $shop['cipher'] . 'sort_fieldcreate_timesort_orderDESCtimestamp' . time() . '{"create_time_lt":' . $create_time_lt . '}' . $shop['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&page_size=50&sort_field=create_time&sort_order=DESC&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $data['create_time_lt'] = $create_time_lt;
                break;
            case 2: //2 查询实时新增的订单
                $last_order = Db::name('order')
                    ->where('shop_id', $shop['id'])
                    ->order('createtime desc')
                    ->find();
                if ($last_order) {
                    $create_time_ge = (int)$last_order['createtime'] + $shop['time_zone'] * 3600 - 60;
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $create_time_ge = (int)1704038400;
                }
                $sign = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'page_size100shop_cipher' . $shop['cipher'] . 'sort_fieldcreate_timesort_orderASCtimestamp' . time() . '{"create_time_ge":' . $create_time_ge . '}' . $shop['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&page_size=100&sort_field=create_time&sort_order=ASC&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $data['create_time_ge'] = $create_time_ge;
                break;
            case 3: //3 查询实时更新的订单
                $last_order = Db::name('order')
                    ->where('shop_id', $shop['id'])
                    ->order('updatetime desc')
                    ->find();
                if ($last_order) {
                    $update_time_ge = (int)$last_order['updatetime'] + $shop['time_zone'] * 3600 - 300;
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $update_time_ge = (int)1704038400;
                }
                $sign = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'page_size50shop_cipher' . $shop['cipher'] . 'sort_fieldupdate_timesort_orderASCtimestamp' . time() . '{"update_time_ge":' . $update_time_ge . '}' . $shop['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&page_size=50&sort_field=update_time&sort_order=ASC&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $data['update_time_ge'] = $update_time_ge;
                break;
            default:
        }

        $return = HttpUtil::tikPostUrl($url, $data, $shop['access_token']);
        $orders = $return['data']['orders']??'';

        if(!$orders)  {
            $update_ordertime_data['updatetime_order_shop'] = time();
            Db::name('shops')
                ->where('id', $shop['id'])
                ->update($update_ordertime_data);
            return json(DefaultResponse(201, false, '暂无数据', null));
        }
        //批量获取数组中的 createtime
        $createtime_arr     = array_column($orders,'create_time');
        $create_time_min    = $shop['time_zone'] ? min($createtime_arr) - $shop['time_zone'] * 3600 :min($createtime_arr);
        foreach ($orders as $order){
            $order['shop_id']   = $shop['id'];
            $order['type']      = $type;
            $order['time_zone'] = $shop['time_zone'];
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_LIST_QUEUE,
                $order,
                false
            );
        }
        $update_ordertime_data['updatetime_order']      = $create_time_min;
        $update_ordertime_data['updatetime_order_shop'] = time();
        Db::name('shops')
            ->where('id', $shop['id'])
            ->update($update_ordertime_data);

        return json(DefaultResponse(200, true, '操作成功!'));
    }




    /**
     * 同步订单详情
     * @param array $orderId
     */
    public function orderUpdate($info=[])
    {

        $orderId = $info['order_id']??'';
        if ($orderId) {
            $orders = Db::name('order')
                ->field('order_id,shop_id,modifystatus')
                ->where('order_id', $orderId)
                ->select()
                ->toArray();
        }else {
            $orders = Db::name('order')
                ->field('order_id,shop_id,modifystatus')
                ->order('createtime desc')
                ->limit(50)
                ->select()
                ->toArray();
        }

        if (!empty($orders)) {
            foreach ($orders as $order) {
                if($order['modifystatus']==1){ //手动修改的订单暂不更新
                    Db::name('order')->where(['order_id'=>$order['order_id']])->update(['updatetime_order'=>time()]);
                }else{
                    //更新详情数据推送队列处理
                    MqTaskPushLogic::mq_task_push(
                        '',
                        MqQueueName::QUEUE_ORDER_INFO_UPDATE_QUEUE,
                        $order,
                        false
                    );

                }
            }
        }

        return json(DefaultResponse(200, true, '操作成功!'));
    }


    /**
     * @desc  手动触发填充客户名称
     * @date  2024/4/13
     * @author  luckyXiong updateJinYiTrackingNumber
     */
    public function updateUserName($info=[]){
        $orderId = $info['order_id']??'';
        $shop    = Db::name('order')
                   ->alias('a')
                   ->leftJoin('ba_shops s', 's.id = a.shop_id')
                   ->where('a.order_id',$orderId )
                   ->field('s.app_key, s.app_secret,s.cipher,s.access_token')
                   ->find();
        if(!$shop)  return [201, false, '暂无数据!'];
        $tik_info = Config::get('Logisticskey.' . 'TIKTOK');
        $baseUrl  = $tik_info['basic_url'];
        $path     = $tik_info['orders_info_path'];
        $sign     = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'ids' . $orderId . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
        $sign     = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url      = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time() . '&ids=' . $orderId;
        $return   = HttpUtil::tikGetUrl($url, $shop['access_token']);
        htmlLog(['response'=>$return,'order_id'=>$orderId],OPERATE_LOG . date('Ym') . '/updateUserName/' . date('Ymd') . '.txt');
        if (!isset($return['data']['orders'][0]) || empty($return['data']['orders'][0]))  return json(DefaultResponse(201, false, '暂无数据!',null));
        $orderinfo = $return['data']['orders'][0];

        if (!empty($orderinfo['recipient_address']['district_info'])) {
            $district_info = $orderinfo['recipient_address']['district_info'];
            foreach ($district_info as $vd) {
                switch ($vd['address_level_name']) {
                    case 'Country':
                        $append_arr['country'] = $vd['address_name'];
                        break;
                    case 'Federal District':
                        $append_arr['state'] = $vd['address_name'];
                        break;
                    case 'State':
                        $append_arr['state'] = $vd['address_name'];
                        break;
                    case 'County':
                        $append_arr['county'] = $vd['address_name'];
                        break;
                    case 'City':
                        $append_arr['city'] = $vd['address_name'];
                        break;
                    default:
                }
            }
        }

        Db::name('order_append')->where('order_id',$orderId)->update(
            [
                'shipping_provider'              => $orderinfo['shipping_provider']??'',
                'shipping_provider_id'           => $orderinfo['shipping_provider_id']??'',
                'buyer_email'                    => $orderinfo['buyer_email']??'',
                'name'                           => $orderinfo['recipient_address']['name']??'',
                'phone_number'                   => $orderinfo['recipient_address']['phone_number']??'',
                'postal_code'                    => $orderinfo['recipient_address']['postal_code']??'',
                'region_code'                    => $orderinfo['recipient_address']['region_code']??'',
                'delivery_option_name'           => $orderinfo['delivery_option_name']??'',
                'payment_method_name'            => $orderinfo['payment_method_name']??'',
                'country'                        =>$append_arr['country']??'',
                'state'                          =>$append_arr['state']??'',
                'county'                         =>$append_arr['county']??'',
                'city'                           =>$append_arr['city']??'',
                'address_detail'                 =>$orderinfo['recipient_address']['address_detail']??'',
                'delivery_option_id'             =>$orderinfo['delivery_option_id']??'',
                'user_id'                        =>$orderinfo['user_id']??'',
                'warehouse_id'                   =>$orderinfo['warehouse_id']??'',
                'json'                           =>json_encode($orderinfo,JSON_UNESCAPED_UNICODE),
            ]
        );

        Db::name('order')->where('order_id',$orderId)->update(
            [
                'tracking_number'=> $orderinfo['tracking_number']??'',
                'status'         => $orderinfo['status']??'',
            ]
        );
        return [200, true, '操作成功!'];
    }




    /**
     * @desc    金蚁自发货回传物流单号生产
     * @date    2024/4/13
     * @author  luckyXiong updateJinYiTrackingNumber
     */
    public function updateJinYiTrackingNumber($param=[]){
           return (new JinyiApiService())->update_tracking_number($param);
    }


    /**
     * @desc    金蚁物流WH单号更新MQ
     * @date    2024/4/13
     * @author  luckyXiong updateJinYiTrackingNumber
     */
    public function updateJinYiTrackingWHNumber($param=[]){
        return (new JinyiApiService())->update_tracking_number_wh($param);
    }


    /**
     * 同步订单结算费
     * @param $type
     * @return mixed
     */
    public function orderStatementListtest($post=[])
    {
        $currentMonth = date('m');
        $currentYear  = date('Y');
        if ($currentMonth == 1) {  
            $lastMonth = 11; // 如果是1月，则上个月是12月  
            $lastYear  = $currentYear - 1; // 上一年  
        } elseif($currentMonth == 2) {  
            $lastMonth = 12;
            $lastYear  = $currentYear - 1;
        }  else {  
            $lastMonth = $currentMonth - 2; // 否则，上个月是当前月份减一  
            $lastYear  = $currentYear; // 年份不变  
        } 

        $times = get_month_time($lastYear,$lastMonth);
        $start_time = $times['first'] - 3600*24*2;
        $end_time   = $times['last'] + 3600*24*31;

        $orders = Db::name('gettrackinfo_copy3_copy1')
            ->field('b.id,a.order_id,a.shop_id,a.createtime,a.status')
            ->alias('b')
            ->join('ba_order a','a.order_id = b.number', 'left')
            ->where('b.time',"=",0)
            // ->count();
            ->limit(10)
            ->select()
            ->toarray();
            // dump($orders);die;

        if(!empty($orders)){
            foreach ($orders as $k=>$order) {
                $shop      = Db::name('shops')->where("id", $order['shop_id'])->find();
                $url = Config('Logisticskey.TIKTOK.basic_url');
                $path = '/finance/202309/orders/' . $order['order_id'] . '/statement_transactions';
                $sign = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url = "https://open-api.tiktokglobalshop.com" . $path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $return = HttpUtil::tikGetUrl($url, $shop['access_token']); 
                // dump($return);die;
                if($return['code']==0 && $return['data']){
                    $this->res_data($return);
                }
                //设置时间
                // $update['statementtime'] = time();
                // Db::name('order')->where('order_id',$order['order_id'])->update($update);
                $update['time'] = time();
                Db::name('gettrackinfo_copy3_copy1')->where('id',$order['id'])->update($update);
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * 同步订单结算费
     * @param $type
     * @return mixed
     */
    public function orderStatementList($post=[])
    {
        $currentMonth = date('m');
        $currentYear  = date('Y');
        if ($currentMonth == 1) {  
            $lastMonth = 11; // 如果是1月，则上个月是12月  
            $lastYear  = $currentYear - 1; // 上一年  
        } elseif($currentMonth == 2) {  
            $lastMonth = 12;
            $lastYear  = $currentYear - 1;
        }  else {  
            $lastMonth = $currentMonth - 2; // 否则，上个月是当前月份减一  
            $lastYear  = $currentYear; // 年份不变  
        } 

        $times = get_month_time($lastYear,$lastMonth);
        $start_time = $times['first'] - 3600*24*2 - 3600*24*60;
        $end_time   = $times['last'] + 3600*24*31;

        $status_array = ["DELIVERED","COMPLETED"];
        $orders = Db::name('order')
            ->field('a.order_id,a.shop_id,a.createtime,a.status,b.updatetime')
            ->alias('a')
            ->join('ba_order_statement b','b.order_id = a.order_id', 'left')
            ->where('a.createtime','between',[$start_time, $end_time])
            // ->where('a.createtime','<=',$end_time)
            // ->whereIn('a.status',$status_array)
            ->where('b.updatetime IS NULL')
            ->limit(2)
            ->group("a.order_id")
            ->order('b.updatetime asc,a.statementtime asc')
            ->select()
            ->toarray();
            // ->count();
        // dump($orders);die;

        if(!empty($orders)){
            foreach ($orders as $k=>$order) {
                $shop      = Db::name('shops')->where("id", $order['shop_id'])->find();
                $url = Config('Logisticskey.TIKTOK.basic_url');
                $path = '/finance/202309/orders/' . $order['order_id'] . '/statement_transactions';
                $sign = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
                $url = "https://open-api.tiktokglobalshop.com" . $path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $return = HttpUtil::tikGetUrl($url, $shop['access_token']); 
                // dump($return);die;
                if($return['code']==0 && $return['data']){
                    $this->res_data($return);
                }
                //设置时间
                $update['statementtime'] = time();
                Db::name('order')->where('order_id',$order['order_id'])->update($update);
                
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * 重置上个月未找到的结算明细
     * @param $type
     * @return mixed
     */
    public function orderStatementListReset($post=[])
    {
        $currentMonth = date('m');
        $currentYear  = date('Y');
        if ($currentMonth == 1) {  
            $lastMonth = 11; // 如果是1月，则上个月是12月  
            $lastYear  = $currentYear - 1; // 上一年  
        } elseif($currentMonth == 2) {  
            $lastMonth = 12;
            $lastYear  = $currentYear - 1;
        }  else {  
            $lastMonth = $currentMonth - 2; // 否则，上个月是当前月份减一  
            $lastYear  = $currentYear; // 年份不变  
        } 

        $times = get_month_time($lastYear,$lastMonth);
        $start_time = $times['first'] - 3600*24*2;
        $end_time   = $times['last'] + 3600*24*31;

        $status_array = ["DELIVERED","COMPLETED"];
        Db::name('order_statement')
            ->alias('b')
            ->join('ba_order a','b.order_id = a.order_id', 'left')
            ->where('a.createtime','between',[$start_time, $end_time])
            ->whereIn('a.status',$status_array)
            ->where('b.status',"Reset")
            ->update([
                'b.status' => "Reset",
            ]);
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
    * 方法详情
    * @param array params
    */
    public function res_data($res_data)
    {
        $statement_data = $res_data['data'];
        if(!empty($statement_data['statement_transactions'])) {
            $order_id = $statement_data['order_id'];
            foreach ($statement_data['statement_transactions'] as $value) {
                $statement_list = [
                    'updatetime' => time(),
                    'order_id' => $order_id,
                    'statement_id' => $value['statement_id'],
                    'statement_time' => ($value['statement_time'] - 16 * 3600),
                    'status' => $value['status'],
                    'transaction_fee_amount' => $value['transaction_fee_amount'],
                    'transaction_id' => $value['id'],
                    'actual_return_shipping_fee_amount' => $value['actual_return_shipping_fee_amount'],
                    'actual_shipping_fee_amount' => $value['actual_shipping_fee_amount'],
                    'adjustment_amount' => $value['adjustment_amount'],
                    'affiliate_commission_amount' => $value['affiliate_commission_amount'],
                    'affiliate_partner_commission_amount' => $value['affiliate_partner_commission_amount'],
                    'after_seller_discounts_subtotal_amount' => $value['after_seller_discounts_subtotal_amount'],
                    'currency' => $value['currency'],
                    'customer_order_refund_amount' => $value['customer_order_refund_amount'],
                    'customer_payment_amount' => $value['customer_payment_amount'],
                    'customer_refund_amount' => $value['customer_refund_amount'],
                    'customer_shipping_fee_amount' => $value['customer_shipping_fee_amount'],
                    'fee_amount' => $value['fee_amount'],
                    'platform_commission_amount' => $value['platform_commission_amount'],
                    'platform_discount_amount' => $value['platform_discount_amount'],
                    'platform_discount_refund_amount' => $value['platform_discount_refund_amount'],
                    'platform_refund_subsidy_amount' => $value['platform_refund_subsidy_amount'],
                    'platform_shipping_fee_discount_amount' => $value['platform_shipping_fee_discount_amount'],
                    'referral_fee_amount' => $value['referral_fee_amount'],
                    'retail_delivery_fee_amount' => $value['retail_delivery_fee_amount'],
                    'retail_delivery_fee_payment_amount' => $value['retail_delivery_fee_payment_amount'],
                    'retail_delivery_fee_refund_amount' => $value['retail_delivery_fee_refund_amount'],
                    'revenue_amount' => $value['revenue_amount'],
                    'sales_tax_amount' => $value['sales_tax_amount'],
                    'sales_tax_payment_amount' => $value['sales_tax_payment_amount'],
                    'sales_tax_refund_amount' => $value['sales_tax_refund_amount'],
                    'settlement_amount' => $value['settlement_amount'],
                    'shipping_fee_amount' => $value['shipping_fee_amount'],
                    'shipping_fee_subsidy_amount' => $value['shipping_fee_subsidy_amount'],
                ];
                $order_statement = Db::name('order_statement')->where('transaction_id',$statement_list['transaction_id'])->find();
                if(!empty($order_statement)){
                    $order_statement = Db::name('order_statement')->where('id',$order_statement['id'])->update($statement_list);
                }else{
                    $order_statement = Db::name('order_statement')->insert($statement_list);
                }
            }
        }else{
            $statement_list['order_id'] = $statement_data['order_id'];
            $statement_list['updatetime'] = time();
            $statement_list['status'] = "NotFound";
            $order_statement = Db::name('order_statement')->insert($statement_list);
        }
        return true;
    }

    /**
     * 同步订单-退款
     * @param $type
     * @return mixed
     */
    public function orderRefundList($post=[])
    {
        $type = $post['type']??'1';
        $shops = Db::name('shops')
            // ->where('id',2)
            ->order("updatetime_refund asc")
            ->find();
        $path = '/return_refund/202309/returns/search';
        switch ($type) {
            case '1':
                 //查询之前的订单
                if (!empty($shops['updatetime_order_refund'])) {
                    $create_time_lt = (int)$shops['updatetime_order_refund'] + 300; //五分钟
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $create_time_lt = (int)time() + $shops['time_zone'] * 3600;
                }
                $sign = $shops['app_secret'] . '' . $path . 'app_key' . $shops['app_key'] . 'page_size50shop_cipher' . $shops['cipher'] . 'sort_fieldcreate_timesort_orderDESCtimestamp' . time() . '{"create_time_lt":' . $create_time_lt . '}' . $shops['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shops['app_secret']);
                $url = "https://open-api.tiktokglobalshop.com" . $path . "?app_key=" . $shops['app_key'] . "&page_size=50&sort_field=create_time&sort_order=DESC&shop_cipher=" . $shops['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $data = array();
                $data['create_time_lt'] = $create_time_lt;
                break;
            //查询实时的订单
            case '2':

                //测试-单个订单
                // $order_ids[0] = "576599320227779328";
                $order_ids = [];
                $data = array();
                $data['order_ids'] = $order_ids;
                $order_ids = json_encode($order_ids,true);

                $last_order_refund = Db::name('order_refund')
                    ->where('shop_id', $shops['id'])
                    ->order('create_time desc')
                    ->find();
                if ($last_order_refund) {
                    $create_time_ge = (int)$last_order_refund['create_time'] - 60;
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $create_time_ge = (int)1672502400;
                }
                $sign = $shops['app_secret'] . '' . $path . 'app_key' . $shops['app_key'] . 'page_size50shop_cipher' . $shops['cipher'] . 'sort_fieldcreate_timesort_orderASCtimestamp' . time() . '{"order_ids":'.$order_ids.',"create_time_ge":' . $create_time_ge . '}' . $shops['app_secret'];
                $sign = hash_hmac('sha256', $sign, $shops['app_secret']);
                $url = "https://open-api.tiktokglobalshop.com" . $path . "?app_key=" . $shops['app_key'] . "&page_size=50&sort_field=create_time&sort_order=ASC&shop_cipher=" . $shops['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
                $data['create_time_ge'] = $create_time_ge;
                break;
            default:
                break;
        }

        $update_ordertime_data = [];
        if(empty($shops['updatetime_order_refund'])){
            $update_ordertime_data['updatetime_order_refund'] = time();
        }else{
            $update_ordertime_data['updatetime_order_refund'] = $shops['updatetime_order_refund'];
        }
        
        $return = HttpUtil::tikPostUrl($url,$data, $shops['access_token']);
        // dump($return);die;
        
        if (isset($return['data']['return_orders']) && !empty($return['data']['return_orders'])) {
            $return_orders = $return['data']['return_orders'];
            foreach ($return_orders as $return_order) {
                $arr = array();
                $arr['shop_id'] = $shops['id'];
                $arr['order_id'] = $return_order['order_id'];
                $arr['return_reason'] = $return_order['return_reason'];
                $arr['return_reason_text'] = $return_order['return_reason_text'];
                $arr['return_status'] = $return_order['return_status'];
                $arr['return_type'] = $return_order['return_type'];
                $arr['create_time'] = $return_order['create_time'];
                $arr['update_time'] = $return_order['update_time'];
                //对比时间
                if($arr['create_time'] < $update_ordertime_data['updatetime_order_refund']){
                    $update_ordertime_data['updatetime_order_refund'] = $arr['create_time'];
                }
                
                $arr['role'] = $return_order['role'];
                //金额
                $arr['currency'] = $return_order['refund_amount']['currency']??'';
                $arr['refund_shipping_fee'] = $return_order['refund_amount']['refund_shipping_fee']??'0';
                $arr['refund_subtotal'] = $return_order['refund_amount']['refund_subtotal']??'0';
                $arr['refund_tax'] = $return_order['refund_amount']['refund_tax']??'0';
                $arr['refund_total'] = $return_order['refund_amount']['refund_total']??'0';
                if(!empty($return_order['refund_amount'])){
                    $arr['cancel_line_items'] = json_encode($return_order, true);
                }
                
                $orderrefund = Db::name('order_refund')->where(['order_id' => $return_order['order_id']])->find();
                if(!empty($orderrefund)){
                    Db::name('order_refund')->where('id',$orderrefund['id'])->update($arr);
                }else{
                    Db::name('order_refund')->insert($arr);
                }
            }
        }
        $update_ordertime_data['updatetime_refund'] = time();
        Db::name('shops')
            ->where('id', $shops['id'])
            ->update($update_ordertime_data);
        return json(DefaultResponse(200, true, '操作成功!'));
    }



    /**
     * @desc     TIK买面单生成PDF失败处理
     * @atuthor  luckyXiong
     * @date     2024-05-11
     */
    public function getTikPdf($params=[]){
           $list = Db::name('order')->field('order_id,shop_id,package_id')->where(
               [
                   'status'             =>'AWAITING_COLLECTION',
                   'shipping_type'      =>'TIKTOK',
                   'shipping_documents' =>'',
               ])

               ->select();
           $list = objectToArray($list);
           $num  = count($list);
           if(!$list)  return  '暂无处理数据';

           $order_ids = array_column($list,'order_id');

           $bach_ids = Db::name('order_shipping_documents_log')->whereIn('order_id',$order_ids)->field('order_id,batch_id')->group('order_id')->select()->toArray();
           $bach_ids_map = array_column($bach_ids,null,'order_id');
           foreach($list as $v){
               $batch_info = $bach_ids_map[$v['order_id']]??[];
               $batch_id   = $batch_info['batch_id']??'';
               $v['batch_id'] = $batch_id;
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_ORDER_DOCUMENT_CHANGE_QUEUE,
                   $v,
                   false);
           }
        return  '处理数据'.$num.'条';
    }


    /**
     * @desc     TIK买面单生成二次获取PDF
     * @atuthor  luckyXiong
     * @date     2024-07-04
     */
    public function getDocumentpdf(){
        $where = [];
        $where[] = ['shipping_documents_status','in',[3,5]];
        $where[] = ['shipping_type','=','TIKTOK'];
        $where[] = ['shipping_documents','=',''];
        $list = Db::name('order')->field('order_id,shop_id')
            ->where($where)->select();
        $list = objectToArray($list);

        if(!$list)  return  '暂无处理数据';
        $order_ids = array_column($list,'order_id');
        $documents = Db::name('order_shipping_documents_log')
            ->field('order_id,shop_id,package_id,batch_id')
            ->where(['status'=>2])
            ->whereIn('order_id',$order_ids)
            ->select();
        $documents = objectToArray($documents);
        if(!$documents)  return  '暂无请求数据';
        $num  = count($documents);
        foreach($documents as $v){
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIKTOK_ORDER_DOC_PDF_QUEUE,
                $v,
                false);
        }
        return  '二次处理数据'.$num.'条';
    }





    /**
     * 订单到每月月底就冻结order表数据
     * @param $type
     * @return mixed
     */
    public function orderFreezeList($post=[])
    {
        $currentMonth = date('m');
        $currentYear  = date('Y');
        if ($currentMonth == 1) {  
            $lastMonth = 12; // 如果是1月，则上个月是12月  
            $lastYear  = $currentYear - 1; // 上一年  
        }else {  
            $lastMonth = $currentMonth - 1; // 否则，上个月是当前月份减一  
            $lastYear  = $currentYear; // 年份不变  
        } 

        $times = get_month_time($lastYear,$lastMonth);
        $start_time = $times['first'];
        $end_time   = $times['last'];
        
        $where = [];
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time];
        $orders = Db::name('order')->where($where)->select()->toArray();  
        if (!empty($orders)) {  
            foreach ($orders as $k => &$order) {
                $order['month'] = $start_time;
                $order['FreezeTime'] = time();
            }
            unset($order);
            Db::name('order_freeze')->where("month",$start_time)->delete();  
            Db::name('order_freeze')->insertAll($orders);  
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }

}

